package com.maduixa.guitar.tabsearch.spring.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HttpServletBean;
import org.springframework.web.servlet.ModelAndView;

import com.maduixa.guitar.tabsearch.spring.business.model.GuitarUser;


@Controller
@Scope ("session")
@RequestMapping({"/users/*"})
public class UsersViewController extends HttpServletBean{

	private static final long serialVersionUID = 2925982589519523762L;
	
	@Autowired com.maduixa.guitar.tabsearch.spring.business.UsersController domainController;
		
	@RequestMapping(value="/login",method=RequestMethod.GET)
    public ModelAndView login(){
		
		ModelAndView result = new ModelAndView();
		
		if(logged()){
			result.setViewName("/error/errorPg");
			result.addObject("error", "You can't login while logged.");
		}
		else {
			result.setViewName("users/loginPg");
		}
		
		return result;			
    }
	
    @RequestMapping(value="/doLogin",method=RequestMethod.POST)
    public ModelAndView doLogin(HttpServletResponse response,
    		@RequestParam("username") String userName, 
    		@RequestParam("password") String password){
		
		ModelAndView result = new ModelAndView();
		String opcio = domainController.validateLogin(userName, password);
	    if (opcio.equals("10")) {
	    	result.setViewName("redirect:/users/mySongs.html");
	    	HttpSession hs = UsersViewController.session();
	    	hs.setAttribute("user", domainController.getUser(userName));
	    	
	    	Cookie c = new Cookie("userAuthentication", userName);
	        c.setMaxAge(7*24*60*60);
	        response.addCookie(c);
	    }
	    else{
	    	result.setViewName("users/loginPg");
	    	result.addObject("error", "Wrong username or password");
        }
    	return result;
    }
 
    @RequestMapping(value="/logout",method=RequestMethod.GET)
    public ModelAndView logout(HttpServletResponse response){
    	
    	HttpSession hs = UsersViewController.session();
    	hs.invalidate();
    	
    	response.setContentType("text/html");
    	Cookie c = new Cookie("userAuthentication", "");
    	c.setMaxAge(0);
    	response.addCookie(c);
    	
    	return new ModelAndView("users/loginPg");
    }
    
    @RequestMapping(value="/mySongs",method=RequestMethod.GET)
    public ModelAndView mySongs(@RequestParam(value ="order", required = false) String order,
    		@RequestParam(value ="direction", required = false) String direction) {
    	
    	if(!logged()) return new ModelAndView("redirect:/users/login.html");
    	
    	ModelAndView result = new ModelAndView("users/mySongsPg");
    	
    	HttpSession hs = UsersViewController.session();
    	GuitarUser gu = (GuitarUser) hs.getAttribute("user");
    	
    	result.addObject("userSongs", domainController.getMySongs(gu.getUsername(),order,direction));
    	result.addObject("viewOnly", false);
    	
    	return result;
    }
    
    @RequestMapping(value="/{username}mySongs",method=RequestMethod.GET)
    public ModelAndView userMySongs(@PathVariable("username") String username,
    		@RequestParam(value ="order", required = false) String order,
    		@RequestParam(value ="direction", required = false) String direction){
    	if(!logged()) return new ModelAndView("redirect:/users/login.html");
    	
    	ModelAndView result = new ModelAndView("users/mySongsPg");

    	GuitarUser gu = domainController.getUser(username);
    	
    	result.addObject("userSongs", domainController.getMySongs(gu.getUsername(),order,direction));
    	result.addObject("viewOnly", true);
    	
    	return result;
    }
    
	@RequestMapping(value="/addMySong",method=RequestMethod.POST)
    public ModelAndView addMySong(@RequestParam("id") long id){
		if(!logged()) return new ModelAndView("redirect:/users/login.html");
        
    	HttpSession hs = UsersViewController.session();
    	GuitarUser gu = (GuitarUser) hs.getAttribute("user");
    	
    	domainController.addUserSong(gu.getUsername(), id, null, null, 0);
    	
        return new ModelAndView("redirect:/songs/search.html");
    }
	
	@RequestMapping(value="/removeMySong",method=RequestMethod.POST)
    public ModelAndView removeMySong(@RequestParam("id") long id){
		if(!logged()) return new ModelAndView("redirect:/users/login.html");
    	
    	domainController.removeMySong(id);
    	
        return new ModelAndView("redirect:/users/mySongs.html");
    }
	
	@RequestMapping(value="/editMySong{id}",method=RequestMethod.GET)
    public ModelAndView editMySong(@PathVariable("id") long id){
		if(!logged()) return new ModelAndView("redirect:/users/login.html");
    	
    	ModelAndView result = new ModelAndView("users/userSongPg");
    	
    	result.addObject("mySong",domainController.getMySong(id));
    	
        return result;
    }
	
	@RequestMapping(value="/doEditMySong",method=RequestMethod.POST)
    public ModelAndView doEditMySong(
    		@RequestParam("id") long id,
    		@RequestParam("record") String record,
    		@RequestParam("cover") String cover,
    		@RequestParam("level") Integer level
    		){
		if(!logged()) return new ModelAndView("redirect:/users/login.html");
    	
    	ModelAndView result = new ModelAndView("redirect:/users/mySongs.html");
    	
    	domainController.updateUserSong(id, record, cover, level);
    	
        return result;
    }
    
    @RequestMapping(value="/viewUsers",method=RequestMethod.GET)
    public ModelAndView viewUsers(){
    	if(!logged()) return new ModelAndView("redirect:/users/login.html");
    	
    	ModelAndView result = new ModelAndView("users/listUsersPg");
    	
    	result.addObject("users", domainController.getAllUsers());
    	return result;
    }
    
    @RequestMapping(value="/editUser",method=RequestMethod.GET)
    public ModelAndView editUser(){
    	if(!logged()) return new ModelAndView("redirect:/users/login.html");
    	
    	ModelAndView result = new ModelAndView("users/editUserPg");

    	return result;
    }
    
    @RequestMapping(value="/doEditUser",method=RequestMethod.POST)
    public ModelAndView doEditUser(
    		@RequestParam("password") String password,
    		@RequestParam("password2") String password2,
    		@RequestParam("mail") String mail
    		){
    	if(!logged()) return new ModelAndView("redirect:/users/login.html");
    	
    	if (password != null && !"".equals(password)) {
			if( password2 == null || !password.equals(password2)){
				ModelAndView result =new ModelAndView("users/editUserPg");
				result.addObject("error", "Password miss match");
				return result;
			}
    	}
    	else 
    		password = null;
    	
    	if ("".equals(mail)) mail = null;
    	
    	HttpSession hs = UsersViewController.session();
    	GuitarUser gu = (GuitarUser) hs.getAttribute("user");
    	hs.removeAttribute("user");
    	
    	gu = domainController.updateUser(gu.getUsername(), password, mail);
    	
    	hs.setAttribute("user", gu);

    	return new ModelAndView("redirect:/users/viewUsers.html");
    }

    public static HttpSession session() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest().getSession(true); // true == allow create
    }
    
    private boolean logged() {
		if(UsersViewController.session().getAttribute("user") != null)
			return true;
		else{
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
			Cookie[] cs = request.getCookies();

			for(int i = 0; i < cs.length; i++){ 
				Cookie c = cs[i];
				if (c.getName().equals("userAuthentication")){
					String userId= c.getValue();
					HttpSession hs = UsersViewController.session();
			    	hs.setAttribute("user", domainController.getUser(userId));
			    	return true;
				}
			}  
			return false;
		}
	}
}